package com.da.auth.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-02-10
 * @Version: 1.0
 */
@Data
public class UserInfo implements UserDetails {
    private String id;
    private String username;
    private String password;
    private Collection<String> roles;

    // 无参构造函数，初始化 roles 为不可变的空集合
    public UserInfo() {
        this.roles = Collections.emptyList();
    }

    // 有参构造函数，对传入的 roles 进行空值检查
    @JsonCreator
    public UserInfo(String id, String username, String password, Collection<String> roles) {
        this.id = id;
        this.username = username;
        this.password = password;
        // 如果 roles 为 null，将其初始化为不可变的空集合
        this.roles = roles == null ? Collections.emptyList() : new ArrayList<>(roles);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 直接对 roles 进行流式操作，由于构造函数确保了 roles 不为 null，这里无需再次检查
        return roles.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}